import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import {
  ProFormCheckbox,
  ProFormText,
  LoginForm,
} from "@ant-design/pro-components";
import { history, Link } from "umi";
import { getImageCodeReq, operationLoginReq } from "./api";

import { TOKEN } from "@/constants";
import { removeAllItem, setItem } from "@/utils/localstorage";
import styles from "../style.less";
import {
  mobileReg,
  mobileRegMessage,
  passWordReg,
  passWordRegMessage,
} from "@/utils/regExp";

message.config({
  maxCount: 1,
});

const Login: React.FC = (props) => {
  const [loginType, setLoginType] = useState<string>("business");
  const [codeObj, setCodeObj] = useState({});
  const formRef = useRef<any>();

  const getImg = async () => {
    const res = await getImageCodeReq({});
    setCodeObj(res);
  };

  useEffect(() => {
    getImg();
  }, []);

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      const res: any = await operationLoginReq({
        ...values,
        clientId: "e5cd7e4891bf95d1d19206ce24a7b32e",
        uuid: codeObj.uuid,
      });
      if (res.code == 200) {
        message.success("登录成功!");
        setTimeout(() => {
          setItem(TOKEN, `Bearer ${res.data.access_token}`);
          if (res.data.lastVenueId) {
            setItem("venueInfo", {
              id: res.data.lastVenueId,
              venueName: res.data.venueName,
            });
            window.location.replace("/welcome");
          } else {
            window.location.replace("/stadium/selectVenue");
          }
        }, 500);
      } else {
        message.error(res.msg);
      }
      // window.location.reload()
      /** 此方法会跳转到 redirect 参数所在的位置 */
      if (!history) return;
    } catch (error) {
      console.log(error);
      message.error("登录失败，请重试！");
    }
  };

  return (
    <LoginForm
      style={{ fontSize: 14 }}
      initialValues={{
        autoLogin: true,
      }}
      actions={
        loginType === "business" && (
          <div>
            <div
              style={{
                marginTop: 24,
                display: "flex",
                justifyContent: "space-between",
              }}
            >
              <a
                onClick={() => {
                  formRef.current && formRef.current.resetFields();
                  setLoginType(loginType === "business" ? "staff" : "business");
                }}
              >
                {loginType === "business" ? "员工登录" : "商家登录"}
              </a>
              <Link to="/user/register">申请入驻{">>"}</Link>
            </div>
          </div>
        )
      }
      onFinish={async (values) => {
        await handleSubmit(values as API.LoginParams);
      }}
      formRef={formRef}
    >
      {loginType === "business" ? (
        <div className={styles.loginTitle}>
          登录<span>(Login)</span>
        </div>
      ) : (
        <div className={styles.loginTitle}>
          员工登录<span>(Employee)</span>
        </div>
      )}
      {loginType === "business" && (
        <ProFormText
          name="username"
          fieldProps={{
            size: "large",
            prefix: <UserOutlined className={styles.prefixIcon} />,
            maxLength: 20,
          }}
          placeholder="请输入登录账号"
          rules={[
            {
              required: true,
              message: "请输入登录账号!",
            },
          ]}
        />
      )}
      {loginType === "staff" && (
        <>
          <ProFormText
            name="tenantId"
            fieldProps={{
              size: "large",
              prefix: <UserOutlined className={styles.prefixIcon} />,
              maxLength: 20,
            }}
            placeholder="请输入品牌编码（可以咨询商家）"
            rules={[
              {
                required: true,
                message: "请输入品牌编码!",
              },
            ]}
          />
          <ProFormText
            name="username"
            fieldProps={{
              size: "large",
              prefix: <UserOutlined className={styles.prefixIcon} />,
              maxLength: 20,
            }}
            placeholder="请输入登录账号"
            rules={[
              {
                required: true,
                message: "请输入登录账号!",
              },
              { pattern: mobileReg, message: mobileRegMessage },
            ]}
          />
        </>
      )}

      <ProFormText.Password
        name="password"
        fieldProps={{
          size: "large",
          prefix: <LockOutlined className={styles.prefixIcon} />,
          maxLength: 20,
        }}
        placeholder="请输入密码"
        rules={[
          {
            required: true,
            message: "请输入密码！",
          },
          { pattern: passWordReg, message: passWordRegMessage },
        ]}
      />
      <div className={styles.codeWrapper}>
        <ProFormText
          name="code"
          style={{ height: "40px" }}
          rules={[
            {
              required: true,
              message: "请输入图片二维码!",
            },
          ]}
          placeholder="请输入图片验证码"
        />
        <img
          onClick={() => getImg()}
          className={styles.codePic}
          src={codeObj.img ? `data:image/png;base64,${codeObj?.img}` : {}}
        />
      </div>
      <div
        style={{
          marginBottom: 24,
          display: "flex",
          justifyContent: "space-between",
        }}
      >
        <ProFormCheckbox noStyle name="autoLogin">
          30天内记住我
        </ProFormCheckbox>
        {loginType === "staff" ? (
          <a
            onClick={() => {
              formRef.current && formRef.current.resetFields();
              setLoginType("business");
            }}
          >
            返回商家登录
          </a>
        ) : (
          <a
            onClick={() => {
              history.push("/user/find");
            }}
          >
            忘记密码?
          </a>
        )}
      </div>
    </LoginForm>
  );
};

export default Login;
